package org.dreamfly.core.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.dreamfly.core.bean.ServerIpInfo;
import org.dreamfly.core.util.ChangeChinese;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


public class UploadFile extends ActionSupport {
    //	private static final String CONTENT_TYPE = "application/octet-stream;charset=UTF-8";
    /**
     * 文件上传根目录
     */
    public static final String uploadFolder = "/upload";

    /**
     * struts2 文件上传 Upload file.
     *
     * @param file         上传文件
     * @param fileName     上传文件名
     * @param uploadFolder 上传至文件夹子类
     * @param className
     * @param isTemp
     * @return 根文件夹以下相对路径
     */
    public static String fileUpload(File file, String fileName, UploadFolder uploadFolder, String className, Boolean isTemp) {
        String root = ServletActionContext.getServletContext().getRealPath(UploadFile.uploadFolder);
        System.out.println("root:" + root);
        File rootFolder = new File(root);
        if (!rootFolder.exists() && rootFolder.mkdir()) ;
        String relativelFolder = generateFolder(root, uploadFolder, className);
        String newFileName = generateFileName(fileName);
        File target = null;
        if(isTemp){
            target = new File(root + "/temp",newFileName);
        }else{
            target = new File(root + "/" + relativelFolder, newFileName);
        }
        try {
            FileUtils.copyFile(file, target);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("relativelFolder:" + relativelFolder);
        if(isTemp){
            return "/temp/" + newFileName;
        }else{
            return relativelFolder + "/" + newFileName;
        }
    }

    /**
     * 文件下载
     *
     * @param response for writer
     * @param fileName 数据库中存储的路径
     * @return 文件名
     */
    public static String fileDownload(HttpServletResponse response, String fileName) {
        try {
            fileName = new String(fileName.getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            System.out.println("url编码不正确");
            e1.printStackTrace();
        }
        String root = ServletActionContext.getServletContext().getRealPath(UploadFile.uploadFolder);
        File fileDown = new File(root + "/" + fileName);
        if (fileDown.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(fileDown);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                int fileLengh = fileInputStream.available();
                byte[] fileBytes = new byte[fileLengh];
                //设置文件大小
                String fileNameTemp = new String(outboxFileName(fileDown.getName()).getBytes(), "ISO-8859-1");
                response.setContentLength(fileLengh);
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition",
                        "attachment;fileName=" + fileNameTemp);
                //输出文件流
                while (true) {
                    int isOver = bufferedInputStream.read(fileBytes);
                    if (isOver == -1) {
                        break;
                    }
                }
                ServletOutputStream out = response.getOutputStream();
                out.write(fileBytes);
                bufferedInputStream.close();
                out.close();
                out.flush();
                response.flushBuffer();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return outboxFileName(fileDown.getName());
        }
        return null;
    }

    public static String remoteFileDownload(HttpServletResponse response, String fileName, ServerIpInfo ipInfo) {
        URL url = null;
        HttpURLConnection con;
        int state = 0;
        try {
            URL temp = new URL("http", ipInfo.getIp(), ipInfo.getPort(), fileName);
            url = ChangeChinese.changeURL(temp);
            con = (HttpURLConnection) url.openConnection();
            state = con.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        File fileDown = new File(fileName);
        if (200 == state) {
            try {
                InputStream fileInputStream = url.openStream();
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                int fileLengh = fileInputStream.available();
                byte[] fileBytes = new byte[fileLengh];
                //设置文件大小
                String fileNameTemp = new String(outboxFileName(fileDown.getName()).getBytes(), "ISO-8859-1");
                ServletOutputStream out = response.getOutputStream();
                response.getWriter().write(url.toString());
                /*response.reset();
                response.setContentLength(fileLengh);
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition",
                        "attachment;fileName=" + fileNameTemp);
                //输出文件流
                while (true) {
                    int isOver = bufferedInputStream.read(fileBytes);
                    if (isOver == -1) {
                        break;
                    }
                    out.write(fileBytes);
                    out.flush();
                }
                bufferedInputStream.close();

                out.close();
                response.flushBuffer();*/
            } catch (Exception e) {
                e.printStackTrace();
            }
            return outboxFileName(fileDown.getName());
        }
        return null;
    }

    /**
     * @param fileName of the will-be deleted file
     * @return true if  the file exists and deleted
     */
    public static boolean fileRemove(String fileName) {
        /*try {
              //此处编码好像有问题，fileName是内部传递的按理说不该转换编码啊
              fileName = new String(fileName.getBytes(""), "UTF-8");
          } catch (UnsupportedEncodingException e1) {
              System.out.println("url编码不正确");
              e1.printStackTrace();
          }*/
        String root = ServletActionContext.getServletContext().getRealPath(UploadFile.uploadFolder);
        //到这里的时候fileName就是乱码了，这个你看看吧。
        File fileDelete = new File(root + "/" + fileName);
        return fileDelete.exists() && fileDelete.delete();
    }

    /**
     * 图片
     */
    private static final String picture = "picture/";
    /**
     * 视频
     */
    private static final String video = "video/";
    /**
     * 音频
     */
    private static final String radio = "radio/";
    /*动作库*/
    private static final String activity = "activity/";
    /*模型*/
    private static final String model = "model/";
    /*暂存*/
    private static final String temp = "temp/";

    private static final String delimiter = "-";

    private static String generateFileName(String fileName) {
        //前缀添加日期
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        //再加上随机数
        int random = new Random().nextInt(100000);
        return df.format(new Date()) + random + UploadFile.delimiter + fileName;
    }

    private static String outboxFileName(String fileName) {
        int position = fileName.indexOf(UploadFile.delimiter);
        if (position == -1) {
            return fileName;
        } else {
            return fileName.substring(++position).replaceAll("[\\t\\s]", "");    //remove the space and tab
        }
    }

    /**
     * @param className    分类名 必须以/结尾
     * @param root         folder
     * @param uploadFolder is a enum
     * @return 相对于根目录的 相对路径
     */
    private static String generateFolder(String root, UploadFolder uploadFolder, String className) {
        //按月创建目录存储
        SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
        String Folder = uploadFolder.toString() + className + df.format(new Date());
        //定位上传目录
        root += "/" + Folder;
        File folder = new File(root);
        if (!folder.exists() && folder.mkdir()) ;
        return Folder;
    }

    /**
     * 上传文件分类文件夹
     */
    public enum UploadFolder {
        /**
         * 图片
         */
        picture(UploadFile.picture),
        /**
         * 视频
         */
        video(UploadFile.video),
        /**
         * 音频
         */
        radio(UploadFile.radio),
        /**
         * 动作库
         */
        activity(UploadFile.activity),
        /*模型*/
        model(UploadFile.model),
        /*暂存*/
        temp(UploadFile.temp);
		private String folder;
		UploadFolder(String folder) {
			this.folder = folder;
		}
		@Override
		public String toString() {
			return this.folder;
		}
	}
}


